package com.cloudservice.ccs.controller;

import com.cloudservice.ccs.biz.ICustomerInfoBiz;
import com.cloudservice.ccs.model.ApiResult;
import com.cloudservice.ccs.entity.CustomerInfo;
import com.cloudservice.ccs.model.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/customer-info")
public class CustomerInfoController {
    @Autowired
    private ICustomerInfoBiz customerInfoBiz;

    @PostMapping("/")
    public ApiResult save(@RequestBody CustomerInfo customerInfo) {
        // 接口问题待讨论：是否应当返回生成的 id？
        customerInfoBiz.save(customerInfo);
        return ApiResult.success();
    }

    @PutMapping("/{id}")
    public ApiResult update(@PathVariable Integer id, @RequestBody CustomerInfo customerInfo) {
        customerInfoBiz.update(id, customerInfo);
        CustomerInfo result = customerInfoBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @DeleteMapping("/{id}")
    public ApiResult delete(@PathVariable Integer id) {
        customerInfoBiz.delete(id);
        return ApiResult.success();
    }

    @GetMapping("/{id}")
    public ApiResult queryById(@PathVariable Integer id) {
        CustomerInfo result = customerInfoBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @GetMapping("/")
    public ApiResult queryAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "0") Integer limit) {
        PageHelper.startPage(page, limit);
        List<CustomerInfo> result = customerInfoBiz.getAll();
        return ApiResult.successWithData(PageData.fromPage((Page<CustomerInfo>) result));
    }

    @PutMapping("/{id}/partial")
    public ApiResult partialUpdate(@PathVariable Integer id, @RequestBody Map<String, Object> fields) {
        customerInfoBiz.partialUpdate(id, fields);
        CustomerInfo result = customerInfoBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @DeleteMapping("/{partial}/deletePartial")
    public ApiResult deletePartial(@PathVariable String partial){
        String []temp=partial.split(",");
        for(String s:temp){
            int id=Integer.parseInt(s);
            customerInfoBiz.delete(id);
        }
        return ApiResult.success();
    }

    @PostMapping("/condition")
    public ApiResult conditionQuery(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "0") Integer limit,@RequestBody Map<String, Object> fields) {
        PageHelper.startPage(page, limit);
        List<CustomerInfo> result = customerInfoBiz.conditionQuery(fields);
        return ApiResult.successWithData(PageData.fromPage((Page<CustomerInfo>) result));
    }
}
